package com.ecreditpal.audio.server.netty;

import com.ecreditpal.audio.netty.message.CustomProtobufDecoder;
import com.ecreditpal.audio.netty.message.CustomProtobufEncoder;
import com.ecreditpal.audio.netty.handler.SubReqClientHandler;
import com.ecreditpal.audio.model.AudioModel;
import com.google.protobuf.ByteString;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/4.
 */
@Slf4j
public class AudioClientBootStrap {
    private int port;
    private String host;
    private SocketChannel socketChannel;

    //    private static final EventExecutorGroup group = new DefaultEventExecutorGroup(20);
    public AudioClientBootStrap(int port, String host) throws InterruptedException {
        this.port = port;
        this.host = host;
        start();
    }

    private void start() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.group(eventLoopGroup);
        bootstrap.remoteAddress(host, port);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
//                ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
//                ch.pipeline().addLast(new ProtobufDecoder(AudioModel.Text.getDefaultInstance()));
//                ch.pipeline().addLast(new CustomPrepender());
//
//                ch.pipeline().addLast(new ProtobufEncoder());
//                ch.pipeline().addLast(new SubReqClientHandler());
                ch.pipeline().addLast(new CustomProtobufDecoder(AudioModel.Text.getDefaultInstance()));
                ch.pipeline().addLast(new CustomProtobufEncoder());
                ch.pipeline().addLast(new SubReqClientHandler());
            }
        });
        ChannelFuture future = bootstrap.connect(host, port).sync();
        if (future.isSuccess()) {
            socketChannel = (SocketChannel) future.channel();
            log.info("connect server  成功");
        }
    }

    /**
     *
     * @param duration 持续时间
     * @param channel 声道数
     * @param byteRate 采样率
     * @param sampleBit 样本位数
     * @return 在duration时间内的声音数据,以byte为单位
     */
    private static int getBufferSize(int duration,int channel, int byteRate,int sampleBit) {
        return duration * channel * byteRate * sampleBit /8;
    }


    public static void main(String[] args) throws InterruptedException, IOException {
//        String result = MyHttpClient.get("http://localhost:7789/server/ribbon/available");
//        JSONObject jsonObject = JSON.parseObject(result);
//        String host  =  jsonObject.getJSONObject("data").getString("host");
//        Integer port  =  jsonObject.getJSONObject("data").getInteger("port");

//        AudioClientBootStrap bootstrap = new AudioClientBootStrap(port, host);
        AudioClientBootStrap bootstrap = new AudioClientBootStrap(36535, "10.8.145.10");

        InputStream is = new FileInputStream("/Users/lifeng/Desktop/dialog4.wav");

        byte[] src = new byte[is.available()];
        is.read(src);
        byte[] data = new byte[src.length - 44];

        int bufferSize = getBufferSize(10,1,16000,16);

        System.arraycopy(src, 44, data, 0, data.length);

        int size = (data.length / bufferSize )+ (data.length % bufferSize == 0 ? 0 : 1);

        int s = 0;
//        for (int i = 0; i < size; i++) {
//            byte[] b = new byte[data.length -s > bufferSize? bufferSize: data.length -s];
//            System.arraycopy(data, s, b, 0, b.length);
//            s += b.length;
//
//            AudioModel.Audio.Builder builder = AudioModel.Audio.newBuilder();
//            builder.setData(ByteString.copyFrom(b));
//            builder.setIndex(i);
//
//            bootstrap.socketChannel.writeAndFlush(builder.build());
//            TimeUnit.SECONDS.sleep(10);
//        }


        for (int ii = 0; ii < 4; ii++) {
            s = 0;
            for (int i = 0; i < size; i++) {
                byte[] b = new byte[data.length -s > bufferSize? bufferSize: data.length -s];
                System.arraycopy(data, s, b, 0, b.length);
                s += b.length;

                AudioModel.Audio.Builder builder = AudioModel.Audio.newBuilder();
                builder.setData(ByteString.copyFrom(b));
                builder.setIndex(i);
                builder.setType(AudioModel.AudioType.REMOTE);

                if (i == size - 1) {
                    builder.setIsLast(true);
                }

                bootstrap.socketChannel.writeAndFlush(builder.build());
                TimeUnit.SECONDS.sleep(10);
            }
        }


//        bootstrap.socketChannel.close();

    }
}
